<?php 
namespace Modules\Core\Middleware;
use Illuminate\Support\Facades\Route;

use Closure;
use Response;
class HandleResponseMiddleware {

  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure  $next
   * @return mixed
   */
  public function handle($request, Closure $next)
  {
      $response = $next($request);

      if (method_exists($response, 'header')) {
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Headers', 'X-Requested-With, Origin, Content-Type, Accept, Authorization');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, DELETE, PATCH, PUT');
        $response->header('Access-Control-Allow-Credentials', 'true');
      }

      // 处理200响应加code加data外壳
      if (method_exists($response, 'status') && $response->status() === 200) {

        if (!$request->is('payment-callback/*')) {
          $response->setContent([
            'code' => 0,
            'message' => '',
            'data' => json_decode($response->content(), true)
          ]);
        }
      }

      return $response;
  }

}